﻿#!/usr/bin/env python
# coding:utf-8
from PoboAPI import *
import datetime
import numpy as np

#Python3Preview
#开始时间，用于初始化一些参数
def OnStart(context) :
    print("I\'m starting...")
    #登录交易账号，需在主页用户管理中设置账号，并把期货测试替换成您的账户名称
    context.myacc = None
    if "回测期货" in context.accounts:
        print("登录交易账号[回测期货]")
        if context.accounts["回测期货"].Login():
            context.myacc = context.accounts["回测期货"]
    g.code_position = GetMainContract('DCE', 'm',20) #得到大连交易所，豆粕的主力合约的持仓信息
    g.code = GetMainContract('DCE', 'm',20)
    print((g.code))
    g.change_flag = 0

def OnMarketQuotationInitialEx(context, exchange,daynight):
    if exchange != 'DCE' or daynight == 'day':
        return
    #获取主力合约
    code1 = GetMainContract('DCE', 'm',20)
    if g.code != code1:
        print("主力合约变更")
        print((g.code))
        g.change_flag = 1
    UnsubscribeBar(g.code,BarType.Min15)
    g.code =code1
    #订阅K线数据，用于驱动OnBar事件
    SubscribeBar(g.code, BarType.Min15) 

    
#K线行情事件，当有新行情出现时调用该事件Ex
def OnBar(context,code,bartype) :
    #过滤掉不需要的行情通知
    if code != g.code:
        print("过滤")
        return
    if g.change_flag == 1:
      #换期时平掉之前的仓位
      QuickInsertOrder(context.myacc,g.code_position,'buy','close',PriceType(PbPriceType.Limit,16,0),10)
      QuickInsertOrder(context.myacc,g.code_position,'sell','close',PriceType(PbPriceType.Limit,16,0),10)
      g.change_flag = 0
    dyndata = GetQuote(g.code)
    #计算均线
    df = GetHisDataAsDF(code,bar_type = BarType.Min15)
    MA = GetIndicator("MA",code,params=(5,10),bar_type = BarType.Min15)
    MA1 = MA["MA(5)"]
    MA2 = MA["MA(10)"]
    print(((MA1-MA2)[-10:]))
    if len(MA2)<2:
        print('error')
        return
    #ma1上穿ma2时买入
    elif MA1[-2] >= MA2[-2] and MA1[-3]<MA2[-3]:
        print("上穿")
        QuickInsertOrder(context.myacc,g.code_position,'buy','close',PriceType(PbPriceType.Limit,16,0),10)
        QuickInsertOrder(context.myacc,g.code,'buy','open',PriceType(PbPriceType.Limit,16,0),10)
        g.code_position = g.code
    #ma1下穿ma2时卖出平仓
    elif MA1[-2] < MA2[-2] and MA1[-3]>=MA2[-3]:
        print("下穿")
        QuickInsertOrder(context.myacc,g.code_position,'sell','close',PriceType(PbPriceType.Limit,16,0),10)
        QuickInsertOrder(context.myacc,g.code,'sell','open',PriceType(PbPriceType.Limit,16,0),10)
        g.code_position = g.code
        